<?php
declare (strict_types=1);

namespace app\madmin\service;

use app\madmin\model\CommissionAssessmentWithdraw as admin;
use app\madmin\model\RechargeRecord;
use app\madmin\model\User;
use app\madmin\model\UserCash;
use app\utils\TrimData;
use think\Exception;

class CommissionAssessmentWithdrawService
{

    /**
     * 查询列表
     * @param int $page
     * @param int $size
     * @param array $data
     * @return array
     * @throws \think\db\exception\DbException
     */
    public function findAll(array $data, int $page = 1, int $size = 10)
    {
        try{
            if (isset($data['agent_name'])) {
                global $user;
                $admin = admin::withoutGlobalScope(['mallId'])->scope('agentSearch', $data)
                    ->where("aw.mall_id", $user->mall_id)
                    ->field('aw.id,withdraw,aw.service_charge,aw.is_online,aw.type,aw.card,aw.serial_num,aw.status,aw.create_time,aw.update_time,a.id agent_id,a.name agent_name');
            } else {
                $admin = admin::field('id,agent_id,withdraw,service_charge,is_online,type,card,serial_num,status,create_time,update_time')
                    ->with('agent');
                $admin = TrimData::searchDataTrim($admin, $data, ['begin_date', 'end_date']);
                $admin = $admin->where($data);
                if (isset($data['is_online']))
                    $admin = $admin->where('is_online', $data['is_online']);
                if (isset($data['status']))
                    $admin = $admin->where('status', $data['status']);
                if (isset($data['type']))
                    $admin = $admin->where('type', $data['status']);
            }
            $list = $admin
                ->order('create_time DESC')
                ->paginate(['page' => $page, 'list_rows' => $size]);
        }catch (\Exception $e){
            dd($e->getMessage());
        }
        
        return [HTTP_SUCCESS, $list];
    }

    /**
     * 读取一条数据
     * @param int $id
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function read(int $id)
    {
        $model = admin::find($id);
        return [HTTP_SUCCESS, $model];
    }
    
    public function update(int $id, array $data)
    {
        $update_time = $data['update_time'];
        unset($data['update_time']);

        $model = admin::where(['update_time' => $update_time])->lock(true)->find($id);

        if (!$model)
            throw new Exception("没有该记录", HTTP_NOTACCEPT);

        $user = User::where(['agent_id' => $model->agent_id])->with('wx')->find();
        if (!$user)
            throw new Exception("用户不是分销人员", HTTP_NOTACCEPT);
        if ($model->getData("status") == 0 && $data['status'] == 2) {
            $update = UserCash::where(['user_id' => $user->id])
                ->dec("assessment_withdraw", (double)$model->withdraw)
                ->inc("assessment", (double)$model->withdraw)
                ->update();
            if (empty($update))
                throw new \PDOException("取消失败");
        } elseif ($model->getData("status") == 0 && !empty($model->is_online) && $data['status'] == 1) {
            switch ($user->wx->type) {
                case 2:
                    $baseIn = "wechat";
                    $method = "wx";
                    break;
                case 1:
                    $baseIn = "wechata";
                    $method = "wx";
                    break;
            }

            $paymentService = new PaymentService();
            $arr = $paymentService->CommissionAssessmentTransfers(
                $baseIn,
                $method,
                $user->wx->openid,
                (double)bcsub((string)$model->withdraw, (string)$model->service_charge)
            );
            if ($arr['return_msg'] == '支付失败')
                throw new Exception($arr['err_code_des'], HTTP_NOTACCEPT);
            $data['pay_no'] = $arr["payment_no"];
            $data['pay_time'] = $arr["payment_time"];
            RechargeRecord::create([
                "user_id" => $user->id,
                'mall_id' => $user->mall_id,
                "base_in" => "admin",
                "source_type" => 2,
                "source" => "推广员提现提现申请:",
                "is_online" => 2,
                'status' => 1,
                "type" => 1,
                "card" => '{}',
                "money" => $model->withdraw,
                "service_charge" => $model->service_charge,
                "remark" => '考核提现扣除余额' . $model->withdraw,
                "trade" => md5(uniqid() . time())
            ]);
        }
        $admin = admin::where('update_time', $update_time)
            ->where('id', $id)
            ->save($data);
        if (!$admin)
            throw new Exception("更新失败", HTTP_NOTACCEPT);
        return [HTTP_CREATED, $admin];
    }

    /**
     * @param $id
     * @return int
     */
    public function delete($id)
    {
        admin::destroy($id);
        return HTTP_NOCONTEND;
    }

    /**
     * 通过提现申请
     * @param int $id
     * @return array
     * @throws Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function adopt(int $id): array
    {
        $find = admin::with(['userId'])->find($id);
        if (empty($find))
            throw new Exception('申请不存在', HTTP_INVALID);
        if ($find->status != 0)
            throw new Exception('申请已经处理', HTTP_INVALID);
        $find->save(['status' => 1]);
        return [HTTP_SUCCESS, $find];
    }

    /**
     * 拒绝提现申请
     * @param int $id
     * @return array
     * @throws Exception
     * @throws \think\db\exception\DataNotFoundExceptionagent_withdraw
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function refuse(int $id): array
    {
        $find = admin::with(['userId'])->find($id);
        if (empty($find))
            throw new Exception('申请不存在', HTTP_INVALID);
        if ($find->status != 0)
            throw new Exception('申请已经处理', HTTP_INVALID);
        $find->save(['status' => 2]);
        $user_cash = UserCash::find($find->user_id);
        $user_cash->inc('assessment', $find->withdraw)->update();
        return [HTTP_SUCCESS, $find];
    }
}
